import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { HighlightComponent } from './highlight.component';
import { Component, Input, ViewChild, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';

@Component({
  template: `
    <lv-highlight #highlightComponent [lvContent]="lvContent" [lvWholeStr]="lvWholeStr"></lv-highlight>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush,
})
class TestHighlightBasicComponent {
  @Input() lvContent: string;
  @Input() lvWholeStr: string;

  @ViewChild('highlightComponent', { static: true }) highlightComponent: HighlightComponent;
}

describe('HighlightComponent', () => {
  beforeEach(waitForAsync(() => {
    TestBed.configureTestingModule({
      declarations: [HighlightComponent, TestHighlightBasicComponent],
    }).compileComponents();
  }));

  describe('render', () => {
    it('should be render correctly', () => {
      const fixture = TestBed.createComponent(HighlightComponent);
      expect(fixture).toMatchSnapshot();
    });
  });

  describe('basic', () => {
    let component: TestHighlightBasicComponent;
    let fixture: ComponentFixture<TestHighlightBasicComponent>;
    let cdr: ChangeDetectorRef;

    beforeEach(() => {
      fixture = TestBed.createComponent(TestHighlightBasicComponent);
      component = fixture.componentInstance;
      cdr = fixture.debugElement.injector.get(ChangeDetectorRef);
    });

    it('should apply wholeStr', () => {
      const str = 'Dorado 6800';
      component.lvWholeStr = str;
      fixture.detectChanges();
      const el = fixture.debugElement.nativeElement;
      const content = el.querySelector('span');
      expect(content.textContent).toContain(str);
    });

    it('should highlighting content', () => {
      const value = 'dorado';
      const str = 'Dorado 6800';
      component.lvContent = value;
      component.lvWholeStr = str;
      fixture.detectChanges();
      const el = fixture.debugElement.nativeElement;
      const content = el.querySelector('.lv-highlight-keyword');
      expect(content.textContent).toContain('Dorado');
    });

    // 当仅仅输入一些特殊正则字符时
    it('should be works correctly with regular characters', () => {
      const keycode = ['$', '(', ')', '*', '+', '.', '[', '?', '\\', '^', '{', '|'];
      const validate = code => {
        const str = 'Dorado 6800';
        component.lvContent = code;
        component.lvWholeStr = `${code}${str}`;
        cdr.detectChanges();
        const el = fixture.debugElement.nativeElement;
        const content = el.querySelector('.lv-highlight-keyword');
        expect(content.textContent).toContain(code);
      };
      keycode.forEach(validate);
    });
  });
});
